<?php

namespace teach\controllers;

use teach\components\WeChat;
use teach\service\CalculationAssemble;
use teach\service\SendWechatMessage;
use teach\service\StarModelAssemble;
use teach\service\Users;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class UsersController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 支付成功后 拼单页面
     * @return \yii\web\Response
     */
    public function actionPaid()
    {
        $request = Yii::$app->request;

        $pid = $request->post('pid'); //拼单产品的id
        $oid = $request->post('oid'); // 订单id
        $sku_id = $request->post('sku_id');//属性表id
        $group_id = $request->post('group_id');//组id

        $msg = '';
        $flag = false;

        if (!$pid) {
            $msg = 'pid 不能为空';
        } elseif (!$oid) {
            $msg = '订单id不能为空';
        } elseif (!$sku_id) {
            $msg = 'sku_id不能为空';
        } elseif (!$group_id) {
            $msg = 'group_id 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $users = new Users();

            $product = $users->productOne($pid, $sku_id);
            if ($product) {
                $order = $users->orderGroup($group_id);
                $product['group'] = $order;
                $jsonData = ResponseHelper::buildJsonData(200, $product);
            }  else {
                $jsonData = ResponseHelper::buildJsonData(400, '获取失败');
            }
        }
        return $this->asJson($jsonData);
    }

    /**
     * 用户查看订单
     * @return \yii\web\Response
     */
    public function actionOrders()
    {
        $request = Yii::$app->request;
        //state = 1 取 status  = -3，-2，-1，1，2，3 全部订单
        //state = 2 取 status = 1 已支付
        //state = 3  取 statues = 2 已发货
        //state = 4 取 status = 3  已完成 --》改成 status = 3 or status = -3
        //state = 5  取 status = -2 申请退款
        //state = 6  待分享 取 status = 1 而且 是在拼单时间允许的范围内
        $uid = $request->post('uid');
        $state = $request->post('state'); //状态 -5退款删除 -4未支付删除 -3退款成功 -2 申请退款 -1 未支付 1 支付 2已发货 3已收货 4收货删除

        $msg = '';
        $flag = false;
        if (!$uid) {
            $msg = 'uid 不能为空';
        } elseif (!$state) {
            $msg = '状态不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $page = $request->post('page');
            $page = $page ? $page : 1;

            if (!in_array($state,[1,2,3,4,5,6])) {
                $jsonData = ResponseHelper::buildJsonData(400, '查询状态有误');
                return $this->asJson($jsonData);
            }

            $users = new Users();
            $where = " uid = {$uid} ";

            switch ($state)
            {
                case 1:
                    $where .= " AND (status = -3 OR status = -2 OR status = -1 OR status = 1 OR status = 2 OR status = 3)";
                    break;
                case 2:
                    $where .= " AND status = 1";
                    break;
                case 3:
                    $where .= " AND status = 2";
                    break;
                case 4:
                    $where .= " AND (status = 3 OR status = -3) ";
                    break;
                case 5:
                    $where .= " AND status = -2 ";
                    break;
                case 6:
                    $time = time();
                    $where .= " AND status = 1 AND effective_time > ({$time} - create_time) "; //TODO  用户订单在有效时间内
                    break;
                default:
                    break;
            }
            $orders = $users->orders($where, $page, $pre_page = 10, $state);
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $orders);
        }
        return $this->asJson($jsonData);
    }

    /**
     * 拼单下用户收货或者删除
     * @return \yii\web\Response
     */
    public function actionOperate()
    {
        $request = Yii::$app->request;
        $oid = $request->post('oid');
        $mid = $request->post('mid');
        $uid = $request->post('uid');
        $state = $request->post('state'); //3收货 -3 未支付 删除

        $msg = '';
        $flag = false;
        if (!$oid) {
            $msg = 'oid 不能为空';
        } elseif (!$mid) {
            $msg = 'mid 不能为空';
        } elseif (!$uid) {
            $msg = 'uid 不能为空';
        } elseif (!$state) {
            $msg = 'state 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            //当传的参数不是2,3,4时，都是非合法参数
            if (!in_array($state, [ 3, -3])) {
                $jsonData = ResponseHelper::buildJsonData(400, '请勿非法操作订单!');
                return $this->asJson($jsonData);
            }

            $users = new Users();
            $time = time();
            $map = " status = {$state} ";


            $param = " id = {$oid} AND mid = {$mid} AND uid = {$uid} ";
            $order = $users->orderOne($param);

            if (!$order) {
                $jsonData = ResponseHelper::buildJsonData(400, '订单不存在,非法操作');
                return $this->asJson($jsonData);
            }

            if ($state == 3) {
                //判断订单是否已经是收货状态
                if ($order['status'] == 3)  {
                    $jsonData = ResponseHelper::buildJsonData(400, '订单已经是收货状态,请勿非法操作');
                    return $this->asJson($jsonData);
                }
                $map .= " , send_time = {$time}";
                $res = $users->orderStatus($map, $param);
                if ($res) {
                    $data = " count_sale = count_sale + {$order['count']}";
                    $where = " id = {$order['pid']}";
                    $users->assembleAdd($data, $where);

                    // 积分入账号用定时脚本执行

                    //查找产品
                    $product = $users->productAssembleOne($order['pid']);
                    if ($product && $product['sub'] == 1) {
                        $calculationAssemble = new CalculationAssemble();
                        var_dump($calculationAssemble->add($oid, $uid, $mid, $order['out_trade_no']));
                    }

                    //给商家跟用户发送已经收货的消息
                    $this->finishGood($order);
                    $jsonData = ResponseHelper::buildJsonData(200, '收货成功');
                    return $this->asJson($jsonData);

                }
            }

            if ($state == -3) {
                $res = $users->orderStatus($map, $param);
                if($res) {
                    $jsonData = ResponseHelper::buildJsonData(200, '修改成功');
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '修改失败');
                }
                return $this->asJson($jsonData);
            }

            $jsonData = ResponseHelper::buildJsonData(400, '非法操作');

        }
        return $this->asJson($jsonData);
    }

    private function finishGood($order)
    {
        $redis = Yii::$app->redis;
        $SendWeChatMessage = new SendWechatMessage();
        //告诉用户已经收货成功
        $tip ="拼团产品收货成功";
        $WeChat = new WeChat();
        while (true) {
            $formid = $redis->rpop("formid_{$order['openid']}");
            $status = $WeChat->sendMsg($SendWeChatMessage->receiveGoods($order['openid'], $formid, $order['out_trade_no'], $tip, $order['create_time'], $order['send_time']));
            if ($status['errcode'] == 0 || $formid == false) {
                break;
            }
        }

        //告诉商家收货成功
        $users = new Users();
        $andWhere = " id = {$order['mid']}";
        $store = $users->userShop($andWhere);
        while (true) {
            $formid_store = $redis->rpop("formid_{$store['openid']}");
            $status_store = $WeChat->sendMsg($SendWeChatMessage->receiveGoods($store['openid'], $formid_store, $order['out_trade_no'], $tip, $order['create_time'], $order['send_time']));
            if ($status_store['errcode'] == 0 || $formid_store == false) {
                break;
            }
        }
    }


}